from django.contrib.auth.mixins import LoginRequiredMixin
import datetime
from django.http import JsonResponse
from django.views import View
from rest_framework.utils import json
from homes.models import House
from order.models import Order
from utils.response_code import RET



class OrdersView(View):
    def get(self, request):
        """获取订单列表"""
        # 1.获取数据
        user = request.user
        role = request.GET.get('role')
        # 判断是否有role参数
        if role is None:
            return JsonResponse({'errno': RET.DATAERR, 'errmsg': '不是房东或房客,你是什么东东?'})
        # 判断是否是房主或房客
        if role != 'custom' and role != 'landlord':
            return JsonResponse({'errno': RET.DATAERR, 'errmsg': '不是房东或房客,你是什么东东?'})

        if role == 'landlord':
            # 若为房东则获取房屋订单记录
            # 链接house数据库
            houses = House.objects.filter(user=user)
            # 获取房东的房屋的house_id
            house_ids = []
            for id in houses:
                house_ids.append(id)
            # house_ids = [house.id for house in houses]
            # 获取该房屋id的订单信息
            orders = Order.objects.filter(house_id__in=house_ids).order_by('-update_time')

        else:
            # 若为房客则获取订单记录
            # 链接订单数据库
            orders = Order.objects.filter(user=user).order_by('-update_time')

        order_list = []
        for order in orders:
            orders = order.to_dict()
            order_list.append(orders)

        return JsonResponse({'errno': RET.OK, 'errmsg': '提交成功', 'data': {'orders': order_list}})

    def post(self, request):
        """添加订单"""
        # 获取数据
        user = request.user
        # 获取json中body中的信息
        data_dict = json.loads(request.body.decode())
        house_id = data_dict.get('house_id')
        start_date = data_dict.get('start_date')
        end_date = data_dict.get('end_date')

        # 验证参数
        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '缺少参数'})

        # 验证是否有该房间
        try:
            house = House.objects.get(id=house_id)
        except:
            return JsonResponse({'errno': RET.DATAERR, 'errmsg': '房屋不存在'})
        # 验证登录用户是否是房主
        if user.id == house.user.id:
            return JsonResponse({'errno': RET.DATAERR, 'errmsg': '房主不可订购自己的房间'})


        # 转换用户输入的时间为可识别时间datetime格式,原本为字符串str格式
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        except Exception:
            return JsonResponse({'errno': RET.DATAERR, 'errmsg': '时间参数错误'})

        # 时间相减,验证为正则入住时间正确
        live_time = (end_date - start_date).days
        if live_time <= 0:
            return JsonResponse({'errno': RET.DATAERR, 'errmsg': '入住时间为负'})

        # 因为可能有人预定多天后开始的房间,因此不能使用获取最大值,要使用查询集获取数量的方法
            # # 时间相减,上一个end时间大于此次start时间则入住订单冲突
            # old_end = Order.objects.get(end_date=max()).days
            # if old_end > start_date:
            #     return JsonResponse({'errno': RET.DATAERR, 'errmsg': '订单冲突'})
        old_filters = {'house': house_id, 'begin_date__gt': end_date, 'end_date': start_date}
        old_date = Order.objects.filter(**old_filters).count()
        # 查询类似:    {old_end  >  start  >  end  >  old_start}
        if old_date >0:
            return JsonResponse({'errno': RET.DATAERR, 'errmsg': '订单冲突'})

        # 计算总金额
        amount = live_time * house.price

        # 生成订单
        order = Order.objects.create(begin_date=start_date, end_date=end_date, days=live_time, house_price=house.price,
                                     amount=amount, status=0, user=user, house=house)

        # 返回订单号
        return JsonResponse({'errno': RET.OK, 'errmsg': '下单成功', 'data': {'order_id': order.id}})



import json
from django.http import JsonResponse
from django.views import View
from order.models import Order
from utils.response_code import RET

# 接收和拒绝订单
class OrderView(LoginRequiredMixin,View):
    def put(self, request, order_id):
        # 接收参数
        user = request.user
        data = request.body.decode()
        order_data = json.loads(data)
        action = order_data.get('action')

        # 验证参数（判断必传参数)
        if action is None:
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数错误'})
        # 判段数据库中是否存在该订单
        try:
            order = Order.objects.get(id=order_id)
            house = order.house
        except Order.DoesNotExist:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '订单不存在'})
        # 订单的房东用户是否和当前用户一致
        if house.user != user:
            return JsonResponse({'errno': RET.ROLEERR, 'errmsg': '用户身份错误'})
        # 判断用户行为
        if action == 'accept':
            order.status = Order.ORDER_STATUS["WAIT_COMMENT"]
            order.save()
        else:
            order.status = Order.ORDER_STATUS["REJECTED"]
            order.save()
            # 保存拒单原因
            reason = order_data.get('reason')
            try:
                order.comment = reason
                order.save()
            except Exception as e:
                return JsonResponse({'errno': e, 'errmsg': '保存失败'})

        return JsonResponse({'errno': RET.OK, 'errmsg': '操作成功'})


# 评价订单
class OrdersCommentView(LoginRequiredMixin,View):
    def put(self, request, order_id):
        user = request.user
        data = json.loads(request.body.decode())
        comment = data.get('comment')

        #       验证参数
        if comment is None:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '评论不能为空'})
        try:
            order = Order.objects.get(id=order_id)
            house = order.house
        except Order.DoesNotExist:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '订单不存在'})
        # 验证用户的一致性
        if user.id != order.user.id:
            return JsonResponse({'errno': RET.ROLEERR, 'errmsg': '用户不一致'})

        # 保存数据,修改状态
        try:
            order.comment = comment
            order.status = Order.ORDER_STATUS["COMPLETE"]
            order.save()
        except Exception as e:
            return JsonResponse({'errno': e, 'errmsg': '保存失败'})

        return JsonResponse({"errno": RET.OK, "errmsg": "评论成功"})


